<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Detail;
use EasyWeChat\Kernel\Messages\News;
use Monolog\Handler\IFTTTHandler;
use think\Db;
use think\Validate;
use app\api\model\OrderSale as OrderSaleModel;
use app\api\model\Order as OrderModel;
use wxpay\Delivery;
use wxpay\Kuaidi;
use wxpay\Wechat;
use wxpay\Wx;

/**
 * 商品接口
 */
class Ordersales extends Api
{
    protected $noNeedLogin = 'logistics';
    protected $noNeedRight = '*';

    /**
     * 申请售后
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function applyrefund()
    {
        $uid = $this->auth->id;

        $id    = $this->request->post('id');
        $gid    = $this->request->post('gid');

        $type  = $this->request->post('type',0);  // 1-退货退款,0-退款无需退货
        $moneye= $this->request->post('money');  // 退款金额
        $cause = $this->request->post('cause');  // 退款原因
        $instructions = $this->request->post('instructions');  // 说明
        $image = $this->request->post('image');  // 图片
        $phone = $this->request->post('phone');  // 电话
        if (!$id) $this->success('请选择订单', '', 400);
        if (!$cause) $this->success('请填写退款原因', '', 400);
        if (!$phone) $this->success('请填写联系电话', '', 400);

        $order = OrderModel::get($id);
        if (!$order) $this->success('订单不存在', '', 400);
        if ($order['uid'] != $uid) $this->success('该订单无法操作', '', 400);
        if ($order['pay_status'] == 0) $this->success('该订单未支付', '', 400);
        if ($order['order_status'] == 0) $this->success('该订单未支付', '', 400);
        if ($order['refund'] == 1) $this->success('已申请退款', '', 400);
        if ($order['refund'] == 2) $this->success('已申请售后', '', 400);

        $response = OrderSaleModel::applysale($uid, $id, $type, $moneye, $cause, $instructions, $image, $phone, $gid);
        if ($response['status'] == true)
        {
            $this->success($response['msg'],'', 200);
        }else{
            $this->success($response['msg'],'', 400);
        }

    }
    /**
     * 查看售后提交信息
     */
    public function saledetails()
    {
        $uid  = $this->auth->id;
        $id   = $this->request->post('id');  // 电话
        $gid  = $this->request->post('gid');  // 电话
        $response = OrderSaleModel::getsale($uid, $id, $gid);

        if ($response)
        {
            $this->success('获取成功',$response, 200);
        }else{
            $this->success('获取失败','', 400);
        }
    }
    /**
     * 上传物流
     */
    public function uplogistics()
    {
        $uid = $this->auth->id;
        $id = $this->request->post('id');  // id
        $invoice = $this->request->post('invoice_no');  // id
        $name = $this->request->post('express_name');  // id

        if (!$id) $this->success('请选择订单', '', 400);
        if (!$invoice) $this->success('请填写单号', '', 400);
        if (!$name) $this->success('请填写快递名称', '', 400);
        $response = OrderSaleModel::setlogistics($uid, $id, $invoice, $name);
        if ($response)
        {
            $this->success('提交成功','', 200);
        }else{
            $this->success('提交失败','', 400);
        }
    }
    /**
     * 订单评论
     */
    public function ordercomment()
    {
        $uid = $this->auth->id;
        $params = $this->request->param();  // id

        if (empty($params['id']) || empty($params['gid']))
        {
            $this->success('缺少参数','',400);
        }
        if (empty($params['goods_comment']))
        {
            $this->success('请填写商品评论内容','',400);
        }
        if (empty($params['goods_score']))
        {
            $this->success('请填写评分','',400);
        }

        if (!empty($params['sid']))
        {
            // 判断
            if (empty($params['shop_comment'])) $this->success('请填写店铺评论内容');
            if (empty($params['shop_score'])) $this->success('请填写评分');
        }

        $response = OrderSaleModel::addrewview($uid, $params);
        if ($response['status'])
        {
            $this->success('评论成功','',200);
        }else{
            $this->success('评论失败','',400);
        }
    }

    /**
     * 未发货退款
     * 退款订单 id
     */
    public function userrefund()
    {
        $uid = $this->auth->id;
        $id  = $this->request->post('id');
        $cause = $this->request->post('cause','');
        $order = OrderModel::get($id);

        if (!$order) $this->success('订单不存在', '', 400);
        if ($order['uid'] != $uid) $this->success('该订单无法操作', '', 400);
        if ($order['pay_status'] == 0) $this->success('该订单未支付', '', 400);
        if ($order['pay_status'] == 2) $this->success('订单已退款，请勿重新操作', '', 200);
        if ($order['order_status'] == 0) $this->success('该订单未支付', '', 400);
        if ($order['order_status'] != 1) $this->success('订单已发货', '', 400);
        if ($order['refund'] == 1) $this->success('已申请退款', '', 400);
        if ($order['refund'] == 2) $this->success('已申请售后', '', 400);
        $order_sale_sn = order_sale_sn();

        $OrderModel = new OrderModel();



        if ($order['user_status'] < 2)
        {
            try {
                $Wx = new Wechat();
                $response = $Wx->refunde($order['pay_sn'], $order_sale_sn, $order['pay_price'], $order['pay_price'], '未发货商品退款');
                $response = json_decode($response,true);
                $info = '200';
            }catch (\Exception $e)
            {
                $info = '100';
            }

            if ($info == '100')
            {
                $this->success('网络延迟，请从新操作', '', 400);
            }

            if ($response['return_code'] == 'SUCCESS' && $response['return_msg'] == 'OK')
            {
                Detail::addPrice($uid,2,$order['pay_price'],time());
                $res = $OrderModel->refund($uid, $order['id'], $response,$cause);
            }

        }else{
            $res = $OrderModel->vip_refund($uid, $order['id'], $order,$cause);
        }

        if ($res['status'] == true)
        {
            $this->success('退款成功', '', 200);
        }else{
            $this->success($res['msg'], '', 400);
        }
    }
    /**
     * 撤销审核
     */
    public function undorefund()
    {
        $id = $this->request->post('id');
        $gid = $this->request->post('gid');

        $uid = $this->auth->id;

        if (empty($id) || empty($gid))
        {
            $this->success('缺少参数','',400);
        }

        $sale = Db::name('order_sale')->where('order_id',$id)->where('order_goods_id',$gid)->find();
        if (!$sale)                   $this->success('该订单不存在', '', 400);
        if ($sale['status'] == 6)     $this->success('该订单已退款', '', 400);
        if ($sale['del'] == 1)        $this->success('该订单已撤销', '', 400);
        if ($sale['user_id'] != $uid) $this->success('该订单无法操作', '', 400);

        $ordermodel = new OrderModel();
        $res = $ordermodel->undo($uid, $sale);

        if ($res)
        {
            $this->success('撤销成功','',200);
        }else{
            $this->success('撤销失败','',400);
        }

    }

    /**
     * 查看物流
     */
    public function logistics()
    {
        $id = $this->request->param('id');
        if (empty($id))
        {
            $this->success('缺少参数','',400);
        }
        $order = OrderModel::get($id);
        if (!$order) $this->success('订单信息不存在','',400);

        $courier = Db::name('courier')
            ->where('orderid',$order['id'])
            ->find();
        if (empty($courier)) $this->success('暂未发货','',400);
        $courier["delivery_name"] = $order["delivery_name"];
        $courier["mobile"] = $order["mobile"];
        

        // $delivery = new Delivery();
        // $response = $delivery->filterReceipt($courier);
        $Kuaidi = new Kuaidi();
        $response = $Kuaidi->synquery($courier);
        
        if ($response['status'] != 200) $this->success($response['msg'],'',400);
        $response["orderId"] = $order["order_sn"];
        $data = $response;
        $this->success('获取成功',$data,200);
    }
}
